require 'net/http'
require 'rubygems'

class RhymeHelper

  TARGET_URL = "http://azarask.in/services/rhyme/?q="
  
  def self.look_up(word)
    begin
      response = Net::HTTP::Proxy(APP_CONFIG[:proxy_addr], APP_CONFIG[:proxy_port]).get_response(URI.parse(TARGET_URL + word.text))
    rescue
      response = nil
    end

    if response
      if response.instance_of?(Net::HTTPOK)
        rhymes = self.parse(response.body)
        word.add_related_terms(:rhy => rhymes) if !rhymes.empty? && word.save
      end
    end
  end

  private

  def self.parse(str)
    str = str.to_s.strip
    str = str[1, str.length-2]
    return [] if str.blank?

    str = '", ' + str
    str = str + ', "'
    arr = str.split(/\", \"/)
    arr.delete_at 0

    words = []
    arr.each do |elem|
      word = Word.find_or_create_by_text(elem.downcase)
      words << word
    end

    words
  end

end
